package com.intelligent.ispc.foundation.poi;

import com.intelligent.ispc.common.utils.ApplicationException;
import org.apache.poi.xssf.usermodel.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.List;

/**
 * Created by Peter on 2016/4/18.
 * Updated by Alice on 2016/8/27 for Tolerance drawExcel
 */
public class SampleExcelBuilder implements ExcelBuilder {
    private static Logger logger = LoggerFactory.getLogger(SampleExcelBuilder.class);

    @Override
    public void drawExcel(String path, ExCellFactory factory) {
        XSSFWorkbook workbook = factory.getCurrentWorkbook();
        List<ExSheet> sheets = factory.getSheets();

        try {
            OutputStream out = new FileOutputStream(path);
            for (int i = 0; i < sheets.size(); i++) {
                drawSheet(workbook, sheets.get(i));
            }
            workbook.write(out);
            out.close();
        } catch (Exception e) {
            logger.error("can not find directory:" + e);
            throw new ApplicationException(e.getMessage());
        }
    }

    protected void drawSheet(XSSFWorkbook workbook, ExSheet exSheet) {
        String name = exSheet.getName();
        logger.debug("sheet name:{}", name);
        List<ExCell> exCells = exSheet.getExCells();
        XSSFSheet sheet = workbook.createSheet(name);
        sheet.setDefaultColumnWidth(30);
        sheet.setColumnWidth(0, 18 * 256);
        sheet.setColumnWidth(1, 30 * 256);
        drawSheet(exCells, sheet, workbook);
    }

    protected void drawSheet(List<ExCell> exCells, XSSFSheet sheet, XSSFWorkbook workbook) {
        for (int i = 0; i < exCells.size(); i++) {
            ExCell exCell = exCells.get(i);
            if (ExCellType.IMAGE.equals(exCell.getCellType())) {
                fillImageToSheet(workbook, sheet, exCell);
            } else if (ExCellType.TEXT.equals(exCell.getCellType())) {
                fillTextToSheet(sheet, exCell);
            }
        }
    }

    private void fillImageToSheet(XSSFWorkbook workbook, XSSFSheet sheet, ExCell exCell) {
        Integer[] c = exCell.getCoordinate();
        String value = exCell.getValue();
        if (c.length < 8) {
            return;
        }

        ByteArrayOutputStream byteArrayOut = new ByteArrayOutputStream();

        BufferedImage bufferImg = null;
        try {
            bufferImg = ImageIO.read(new File(value));
            ImageIO.write(bufferImg, "png", byteArrayOut);
            XSSFDrawing patriarch = sheet.createDrawingPatriarch();
            XSSFClientAnchor anchor = new XSSFClientAnchor(c[0], c[1], c[2], c[3], c[4].shortValue(), c[5], c[6].shortValue(), c[7]);
            anchor.setAnchorType(3);
            patriarch.createPicture(anchor, workbook.addPicture(byteArrayOut.toByteArray(), XSSFWorkbook.PICTURE_TYPE_JPEG));

        } catch (Exception e) {

            logger.error("can not find file:" + e);
            throw new ApplicationException(e.getMessage());
        }
    }

    private void fillTextToSheet(XSSFSheet sheet, ExCell exCell) {
        Integer[] coordinate = exCell.getCoordinate();
        String value = exCell.getValue();
        XSSFCellStyle hssfCellStyle = exCell.getStyle();

        if (coordinate.length < 2) {
            return;
        }

        int x = coordinate[0].intValue();
        int y = coordinate[1].intValue();

        XSSFRow row = sheet.getRow(x);

        if (row == null) {
            row = sheet.createRow(x);
            row.setHeight((short) (20 * 15));
        }

        XSSFCell cell = row.getCell(y);
        if (cell == null) {
            cell = row.createCell(y);
        }

        if (hssfCellStyle != null) {
            cell.setCellStyle(hssfCellStyle);
        }
        XSSFRichTextString text = new XSSFRichTextString(value);
        cell.setCellValue(text);
    }

}
